package com.ck.ck_back.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.ck.ck_back.dao.FocusMapper;
import com.ck.ck_back.dao.HistoryMapper;
import com.ck.ck_back.dao.UserMapper;
import com.ck.ck_back.pojo.*;
import com.ck.ck_back.service.userservice;
import com.ck.ck_back.utils.FileUtil;
import com.ck.ck_back.utils.md5_add;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class userImpl implements userservice {
    @Resource
    private UserMapper userMapper;
    @Value("${uploadPathImg}")
    private String uploadPathImg;
    @Resource
    private FocusMapper focusMapper;

    @Transactional
    @Override
//    返回参数，0是用户已在表中的，1是插入成功的，403是参数错误，404参数为空
    public int adduser(User user) {
        if (user != null){
            List<User> users = userMapper.selectalluser();
//        查询是否已经有该用户
            for (User u:users
            ) {
                if (u.getOpenid().equals(user.getOpenid())){
//                如果数据库中有该用户的openid，说明这是一个老用户
                    return 0;
                }
            }

//        如果不是老用户--即是新用户，插入数据库
            user.setRegisterTime(new Date().getTime());
            userMapper.insert(user);
            return 1;
        }else if(user.getOpenid()==null||user.getName()==null||user.getAvatarurl()==null||user.getIdentity()==null){
            return 403;
        }else {
            return 404;
        }

    }


//    返回参数时，404为参数为空，0/1为身份识别码，2为查无此人
    @Override
    public int identity(String openid) {
        if (openid != null && !openid.equals("")){
            User user = userMapper.selectByPrimaryKey(openid);
            if (user != null){
                return userMapper.selectidentity(openid)?1:0;
            }else {
                return 2;
            }
        }else {
            return 404;
        }
    }

//    修改用户身份，404参数错误，2无此人，0,1身份码，切换身份会自动补成作者身份密码
    @Transactional
    @Override
    public int changeidentity(String openid) {
        if(openid != null && !openid.equals("")){
            User user = userMapper.selectByPrimaryKey(openid);
            System.out.println(user.toString());
            if (user != null){
//                不是作者时
                if (user.getIdentity() == false){
//                    String[] randompwd= UUID.randomUUID().toString().split("-");
//                    String truepwd=randompwd[0]+randompwd[1];
                    User user_new_info = new User();

                    user_new_info.setOpenid(openid);
                    user_new_info.setIdentity(!user.getIdentity());
//                   生成账号（openid）和随机密码
                    user_new_info.setAuthorUsername(openid);
//                    数据库密码使用双重加密
                    user_new_info.setAuthorPwd(md5_add.md5PlusSalt(openid));
                    userMapper.updateByPrimaryKeySelective(user_new_info);
                    return userMapper.selectByPrimaryKey(openid).getIdentity()?1:0;
                }else {
                    User user_new_info = new User();
                    user_new_info.setOpenid(openid);
                    user_new_info.setIdentity(!user.getIdentity());
                    user_new_info.setAuthorUsername("");
                    user_new_info.setAuthorPwd("");
                    userMapper.updateByPrimaryKeySelective(user_new_info);
                    return userMapper.selectByPrimaryKey(openid).getIdentity()?1:0;
                }
            }else {
                return 2;
            }
        }else{
            return 404;
        }
    }

//    重置作者端密码 0重置成功，1身份错误，2查无此人，404参数错误
    @Transactional
    @Override
    public int resetauthor(String openid) {
        if (openid != null &&!openid.equals("")){
            User user= userMapper.selectByPrimaryKey(openid);
            if (user != null ){
                if(user.getIdentity() == true){
                    // 使用uuid生成一个8位的随机数作为密码
                    String[] randompwd= UUID.randomUUID().toString().split("-");
                    String truepwd = randompwd[0]+randompwd[1];
                    User user_new_info = new User();
                    user_new_info.setOpenid(openid);
                    user_new_info.setAuthorUsername(openid);
                    //                    数据库密码使用双重加密
                    user_new_info.setAuthorPwd(md5_add.md5PlusSalt(truepwd));
                    userMapper.updateByPrimaryKeySelective(user_new_info);
                    return 0;
                }else {return 1;}

            }else {
                return 2;
            }
        }else {
            return 404;
        }
    }


//    该方法暂不能用，因为删除事关重大，需要验证管理身份
    @Transactional
    @Override
    public String deleteuser(String openid) {
//        查询是否拥有此用户
        User user = userMapper.selectByPrimaryKey(openid);
        if (user !=null){
            userMapper.deleteByPrimaryKey(openid);
            return "删除成功";
        }else {
            return "该用户未在数据库或已被删除";
        }
    }

//    查询所有人的数量
    @Override
    public int selectalluser() {
       List<User> users = userMapper.selectalluser();
       int num =users.size();
        return num;
    }

//    根据openid返回用户信息
    @Override
    public User selectbyopenid(String openid) {
        if(openid !=null && !openid.equals("")){
            System.out.println(userMapper.selectByPrimaryKey(openid));
//            try {
//                StpUtil.getLoginId();
//                System.out.println(StpUtil.getLoginId());
//            } catch (Exception e) {
//                System.out.println(e);
//            }
            return userMapper.selectByPrimaryKey(openid);
        }else {
            return null;
        }
    }

//    更改作者端的密码,1为正确，2表示身份错误，404参数错误
    @Transactional
    @Override
    public int updateAuthor(String openid,String pwd) {
        if(openid !=null && !openid.equals("") && pwd !=null && !pwd.equals("")){
           User user= userMapper.selectByPrimaryKey(openid);
           if (user.getIdentity() == false){
               return 2;
           }else {
               User user_new_info = new User();
               user_new_info.setOpenid(openid);
//               双重加密
               user_new_info.setAuthorPwd(md5_add.md5plussalt(pwd));
               userMapper.updateByPrimaryKeySelective(user_new_info);
               System.out.println(userMapper.selectByPrimaryKey(openid));
               return 1;
           }
        }else {
            return 404;
        }
    }

//    实现登陆，0为登陆成功,1为密码错误，2为身份错误，3无此人，404参数错误
    @Override
    public int login(String openid, String pwd) {
//        判断参数是否完整
        if (openid !=null && !openid.equals("") && pwd != null && !pwd.equals("")){
           User user =  userMapper.selectByPrimaryKey(openid);
            System.out.println(user);
//           判断数据库中是否有此人
           if (user != null){
//               判断此人是否是作者
               if (user.getIdentity() == true){
//                   判断密码
                   if(pwd.equals(md5_add.md5MinusSalt(user.getAuthorPwd()))){
//                       StpUtil.login(user.getOpenid());

                       return 0;
                   }else {return 1;}
               }else {return 2;}
           }else {
               return 3;
           }
        }else {
            return 404;
        }
    }

//    查询作者个人详细信息 0正常，1身份错误，2查无此人，404参数错误
    @Override
    public int selectauthor(String openid) {
        if( openid !=null && !openid.equals("") ){
            User user = userMapper.selectByPrimaryKey(openid);
            if (user != null){
//                判断此人是否为作者
                if (user.getIdentity() == true){
                    return 0;
                }else {return 1;}
            }else {return 2;}
        }else {return 404;}
    }

//    更新用户信息 , 404参数错误 ， 1正常 ，2更新错误 ，3 查无此人
    @Transactional
    @Override
    public int updateUser(User user) {
        if (user !=null && !user.equals("")){
//            判断是否有该用户
            User user1 = userMapper.selectByPrimaryKey(user.getOpenid());
            System.out.println(user);
            System.out.println(user1);
            if (user1 != null){
//                生成一个新的用户用来更新

//                传入的密码不为空时，才进行密码修改
                if (user.getAuthorPwd() != null){
                    user.setAuthorPwd(md5_add.md5plussalt(user.getAuthorPwd()));
                }
                int result = userMapper.updateByPrimaryKeySelective(user);
                System.out.println(result);
                if (result == 1){return 1;}else {
                    return 2;
                }

            }else {return 3;}
        }else {
            return 404;
        }

    }

//    根据openid查询用户的所有信息,404参数错误，5查无此人，4,身份错误
    @Override
    public Object select_author_production(String openid,int state) {
        System.out.println(userMapper.select_author_production(openid,state));
        if( openid !=null && !openid.equals("") ){
//            User user = userMapper.select_author_production(openid,state);
//            if (user != null){
//                if (user.getIdentity() !=true){
//                    return 1;
//                }else {return 4;}
//            }else {return 5;}

            return userMapper.select_author_production(openid,state);
        }else {
            return null;
        }
    }

    //    上传文件,404参数错误
    @Override
    public String upload(MultipartFile file) {
        System.out.println(file);
        if (file != null){
            String filename = FileUtil.upload(file,uploadPathImg,file.getOriginalFilename());
            return filename;
        }else {
            return "404";
        }
    }

    @Override
    public List<User> getaudit() {
        return userMapper.getallwaitaudit();
    }

    @Override
    public int updatestate(String openid,int state) {
        if (openid!=null&&!openid.equals("")){
            User user = userMapper.selectByPrimaryKey(openid);
            if (user!=null){
                user.setState(state);
                int result = userMapper.updateByPrimaryKeySelective(user);
                if (result==1){
                    return result;
                }else {return 2;}
            }else {return 3;}
        }else {return 404;}
    }

}
